﻿using System;

namespace Love.Awesome.Grite
{
    /// <summary>
    /// GIF 转换为 PNG 格式的精灵图。
    /// </summary>
    public static class GIF2SpriteSheetConverter
    {
        private const int MaxPerRow = 8;

        public static string Convert(string imagePath)
        {
            if (System.IO.Path.GetExtension(imagePath).ToLower() != ".gif")
                throw new Exception("该文件拓展名不是 gif！");

            if (!System.IO.File.Exists(imagePath))
                throw new Exception($"{imagePath} 不存在！");

            // Load the image
            var inputImage = SixLabors.ImageSharp.Image.Load(imagePath);
            var frameCount = inputImage.Frames.Count;
            var frameWidth = inputImage.Frames[0].Width;
            var frameHeight = inputImage.Frames[0].Height;

            // Create a new image
            var spriteSheet = new SpriteSheet(frameCount, frameWidth, frameHeight);
            for (var i = 0; i < inputImage.Frames.Count; i++)
            {
                var img = inputImage.Frames.CloneFrame(i);
              
                spriteSheet.AddImage(img);
            }
              
            // Validate the path
            var newPath = imagePath.Substring(0, imagePath.Length - 4) + ".png";

            // Save the image
            spriteSheet.Save(newPath);
            return newPath;
        }


    }
}
